// pages/editWord.js
const recorderManager = wx.getRecorderManager()
const innerAudioContext = wx.createInnerAudioContext()
const util = require('../../utils/util.js')
Page({
  /**
   * 页面的初始数据
   */
  data: {
    receiveDic: null, //上页面带过来的参数 section_type text voice addType：add 和change
    lastText: '',
    lastRecorderFilePath: '', // 录音地址
    recording: false, //是否录制语音 默认为NO
    focus: true,
    voiceBtnTitle: '',
    playDuration: '', // 播放时间
    playState: false, // 播放状态样式判断
    voice: false, // 预览语音显示
    voiceIconName: '../../image/produce/voiceIcon1.png',
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    console.log("接收到的参数是obj=" + options.receiveDic); //此处打印出来的仅仅是字符串 需要解析，解析如下
    this.setData({
        receiveDic: JSON.parse(options.receiveDic)
      }),
      this.setData({
        lastRecorderFilePath: this.data.receiveDic.section_type == 3 ? '' : this.data.receiveDic.voice, //视频情况下语音为‘’
        lastText: this.data.receiveDic.text
      })

    if (this.data.lastRecorderFilePath) {
      //获取语音时长
      innerAudioContext.src = this.data.receiveDic.voice;
    }

    //音频进入可以播放状态，但不保证后面可以流畅播放
    innerAudioContext.onCanplay(() => {
      console.log(innerAudioContext.duration) //0
    })
    setTimeout(() => {
      console.log(innerAudioContext.duration) //2.795102
      this.setData({
        playDuration: Math.ceil(innerAudioContext.duration) //向上取整
      })
    }, 1000)
    //音频播放回调
    innerAudioContext.onPlay(() => {
        // console.log('开始播放')
        //话筒帧动画  
        var i = 1;
        var index = 1;
        var that = this;
        this.timer = setInterval(function() {
          i++;
          i = i % 3;
          that.setData({
            voiceIconName: '../../image/produce/voiceIcon' + i + '.png'
          })
        }, 500);
      }),
      innerAudioContext.onError((res) => {
        wx.showToast({
          title: res.errMsg,
          icon: 'none',
          duration: 2000
        })
      }),
      // 播放结束
      innerAudioContext.onEnded((res) => {
        clearInterval(this.timer) //暂停话筒帧动画
        this.setData({
          onPlay: false,
          voiceIconName: '../../image/produce/voiceIcon1.png'
        })
      }),
      // 播放结束
      innerAudioContext.onStop((res) => {
        clearInterval(this.timer) //暂停话筒帧动画
        this.setData({
          onPlay: false,
          voiceIconName: '../../image/produce/voiceIcon1.png'
        })
      }),

      //录音事件回调
      recorderManager.onStart(() => {
        wx.showLoading({
          title: '录音中...',
        })
      })
    //错误回调
    recorderManager.onError((res) => {
      console.log(res);
      wx.hideLoading();
      wx.showToast({
        title: res,
        icon: 'success',
        duration: 1000
      })
    })
    recorderManager.onStop((res) => {
      wx.hideLoading();
      const {
        tempFilePath,
        duration
      } = res

      let recorderTempFilePath = tempFilePath;
      //要大于三秒
      if (duration < 3000) {
        wx.showToast({
          title: '录音时间太短',
          icon: 'none',
          duration: 1000
        })
      } else {
        console.log('本地录音路径' + recorderTempFilePath)
        let playDuration = Math.ceil(duration / 1000);
        this.setData({
          playDuration: playDuration,
          lastRecorderFilePath: recorderTempFilePath,
          voice: true
        })
      }
    })
  },
  //录音文本切换
  voiceChange: function() {
    this.setData({
      recording: !this.data.recording,
      voiceBtnTitle: this.data.recording ? '' : '按住说话'
    })
  },

  //长按进行录制音频
  record: function() {
    console.log('录音')
  },

  //获取文本
  getAreaWord: function(e) {
    console.log(e.detail.value)
    this.setData({
      lastText: e.detail.value
    })
  },

  //播放语音
  playVocie: function() {
    var that = this;
    this.setData({
      playState: !that.data.playState
    })
    if (that.data.playState) {
      //播放
      console.log('播放本地语音')
      let recorderTempFilePath = that.data.lastRecorderFilePath;
      innerAudioContext.autoplay = true;
      innerAudioContext.src = recorderTempFilePath;
      innerAudioContext.play();
    } else {
      //停止
      console.log('停止播放')
      innerAudioContext.stop();
    }

  },
  //键盘完成事件
  losefocusKeybord: function() {
    this.setData({
      focus: false
    })
  },
  //键盘聚焦
  focusKeybord: function() {
    this.setData({
      focus: true
    })
  },

  /* 上传语音到阿里云*/
  uploadVocieFile: function() {
    var that = this;
    util.uploadOssFile(that.data.lastRecorderFilePath, "/Record/",
      function(voiceUrl) {
        console.log("录音路径为" + voiceUrl)
        that.getBack(voiceUrl, that);
      },
      function(res) {
        console.log("上传失败")
      });
  },

  //确定 上传服务器 并且 携带语音 将数据返回到上个页面
  getBack: function(voice, that) {
    console.log('当前处理的章节stype是' + that.data.receiveDic.section_type)
    if (that.data.receiveDic.addType == 'add') {
      //新增一个文本章节 默认从1开始
      var sectionOrderIndex = that.data.receiveDic.count - 1; //最后一个view的order + 1
      var sectionOrder = that.data.receiveDic.count == 2 ? '1' : sectionOrderIndex.toString();
      const dic = {
        knowledge_id: that.data.receiveDic.knowledge_id,
        section_order: sectionOrder, //默认从1开始
        section_type: '1', //文本为1
        struct_order: '1', //固定写1
        text: that.data.lastText,
        voice: voice,
      }
      //提交
      that.uploadSectionData(util.SectionHandle, 'POST', dic, that);
    } else if (that.data.receiveDic.addType == 'replace') {
      //章节替换为文本章节
      const dic = {
        text: that.data.lastText,
        voice: voice,
        section_type: '1', //文本为1
      }
      //提交
      that.uploadSectionData(util.SectionHandle + that.data.receiveDic.id + '/', 'PUT', dic, that);
    } else {
      //修改所有章节的文本
      if (that.data.receiveDic.section_type == 3) {
        //视频只能更改文本
        const dic = {
          text: that.data.lastText
        }
        //提交
        that.uploadSectionData(util.SectionHandle + that.data.receiveDic.id + '/', 'PUT', dic, that);
      } else {
        const dic = {
          text: that.data.lastText,
          voice: voice,
        }
        //提交
        that.uploadSectionData(util.SectionHandle + that.data.receiveDic.id + '/', 'PUT', dic, that);
      }

    }
  },
  //更新章节内容
  uploadSectionData: function(url, method, dic, that) {
    util.publicRequestWithToken(
      url,
      method,
      dic,
      //sucess
      function(data) {
          //返回
          if (that.data.receiveDic.addType == 'add') {
            //添加章节
            var tempDic = {
              section_type: data.detail.section_type,
              text: data.detail.text,
              voice: data.detail.voice,
              id: data.detail.id,
              section_order: data.detail.section_order,
              knowledge_id: data.detail.knowledge_id
            }
            that.processData(tempDic)
          } else if (that.data.receiveDic.addType == 'replace') {
            var tempDic = {
              text: data.detail.text,
              voice: data.detail.voice,
            }
            that.replaceData(tempDic, that)
          } else {
            //修改章节 图片可以传语音 视频没有
            if (that.data.receiveDic.section_type == '3') {
              var tempDic = {
                text: data.detail.text,
              }
              that.replaceData(tempDic, that)
            } else {
              var tempDic = {
                text: data.detail.text,
                voice: data.detail.voice,
              }
              that.replaceData(tempDic, that)
            }

          }
      },
      //fail
      function(error) {
        wx.showToast({
          title: '网络开小差了',
          icon: 'none'
        })
      },
    );
  },

  //更新章节里面的text和voice
  replaceData: function(dic, that) {
    console.log('返回')
    var pages = getCurrentPages();
    var prevPage = pages[pages.length - 2]; //上一个页面
    //直接调用上一个页面的setData()方法，把数据存到上一个页面中去
    var tempArr = prevPage.data.dataArr;

    var replaceDic = tempArr[that.data.receiveDic.index];

    if (that.data.receiveDic.section_type == '3') {
      //视频只能更改文本
      replaceDic.text = dic.text;
    } else {
      replaceDic.text = dic.text;
      replaceDic.voice = dic.voice;
    }
    tempArr.splice(that.data.receiveDic.index, 1, replaceDic); //指定位置替换掉数据
    console.log(tempArr);
    prevPage.setData({
      //处理上个页面的dataArr
      dataArr: tempArr
    })
    wx.navigateBack({
      delta: 1,
    })
  },
  //新增章节 数组里添加一个
  processData: function(dic) {
    console.log('返回')
    var pages = getCurrentPages();
    var prevPage = pages[pages.length - 2]; //上一个页面
    //直接调用上一个页面的setData()方法，把数据存到上一个页面中去

    var lastArr = prevPage.data.dataArr;
    lastArr.splice(lastArr.length - 1, 0, dic); //在倒数第二位置插入新元素，并返回新的Array
    console.log(lastArr);
    prevPage.setData({
      //处理上个页面的dataArr
      dataArr: lastArr,
      pandectValue: lastArr.length - 2
    })

    wx.navigateBack({
      delta: 1,
    })
  },
  //确定并返回
  sure: function() {
    //如果存在语音 则要先提交到阿里云
    if (this.data.lastRecorderFilePath.length > 0) {
      innerAudioContext.destroy(); //销毁当前实例
      this.uploadVocieFile();
    } else {
      this.getBack('', this);
    }
  },

  startRecord: function() {
    console.log('开始长按录音')
    //键盘聚焦
    this.setData({
      voiceBtnTitle: '松开结束'
    })
    const options = {
      duration: 1800000, //指定录音的时长 3分钟
      sampleRate: 44100,
      numberOfChannels: 1,
      encodeBitRate: 192000,
      format: 'mp3',
      frameSize: 50
    }
    // 开始录音
    recorderManager.start(options);
    innerAudioContext.stop();

  },
  endRecord: function() {
    console.log('结束录音')
    this.setData({
      voiceBtnTitle: '按住说话'
    })
    let that = this;
    // 结束录音
    recorderManager.stop();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})